﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using FluentNHibernate.Cfg.Db;
using FluentNHibernate.Cfg;
using System.Configuration;
using FluentNHibernate.Automapping;
using MvcMovie.Models;
using NHibernate;
using NHibernate.Cfg;
using NHibernate.Tool.hbm2ddl;


namespace MvcMovie.Util
{
    public class NHibernateUtil
    {
        private static ISessionFactory  sessionFactory;

        static NHibernateUtil()
        {
            sessionFactory = CreateSessionFactory();
        }

        private static ISessionFactory CreateSessionFactory()
        {
            var automappingConfiguration = new MovieConfiguration();
            return Fluently.Configure()
                           .Database(MsSqlConfiguration.MsSql2008.ConnectionString(c => c.FromConnectionStringWithKey("ApplicationServices"))
                           .ShowSql())
                           .Mappings(m => m.AutoMappings.Add(AutoMap.AssemblyOf<Movie>(automappingConfiguration)))
                           .ExposeConfiguration(BuildSchema)
                           .BuildSessionFactory();
        }

        private static void BuildSchema(NHibernate.Cfg.Configuration config)
        {
                new SchemaUpdate(config).Execute(true, true);
        }

        public static ISession GetSession()
        {
            return sessionFactory.OpenSession();
        }
    }
}